<template>
  <div class="business-type-container">
    <div class="page-header">
      <h2 class="page-title">业务类型管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateBusinessType">
          <el-icon><Plus /></el-icon>新建业务类型
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="业务名称">
          <el-input v-model="filterForm.name" placeholder="请输入业务名称" clearable />
        </el-form-item>
        <el-form-item label="业务代码">
          <el-input v-model="filterForm.code" placeholder="请输入业务代码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 业务类型表格 -->
    <div class="business-type-table">
      <el-table
        :data="displayBusinessTypeList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="code" label="业务代码" width="100" />
        <el-table-column prop="name" label="业务名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="avgServeTime" label="平均服务时间" width="120">
          <template #default="scope">
            {{ formatTime(scope.row.avgServeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEditBusinessType(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDeleteBusinessType(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑业务类型对话框 -->
    <el-dialog
      v-model="businessTypeDialog.visible"
      :title="businessTypeDialog.isEdit ? '编辑业务类型' : '新建业务类型'"
      width="600px"
    >
      <el-form
        ref="businessTypeFormRef"
        :model="businessTypeForm"
        :rules="businessTypeRules"
        label-width="100px"
      >
        <el-form-item label="业务代码" prop="code">
          <el-input 
            v-model="businessTypeForm.code" 
            placeholder="请输入业务代码，如A、B等" 
            :disabled="businessTypeDialog.isEdit"
            maxlength="3" 
          />
        </el-form-item>
        <el-form-item label="业务名称" prop="name">
          <el-input v-model="businessTypeForm.name" placeholder="请输入业务名称" />
        </el-form-item>
        <el-form-item label="平均服务时间" prop="avgServeTime">
          <el-input-number 
            v-model="businessTypeForm.avgServeTime" 
            :min="1" 
            :max="60" 
            :step="1" 
            placeholder="平均服务时间(分钟)" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="businessTypeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="businessTypeForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入业务类型描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="businessTypeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitBusinessTypeForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

export default {
  name: 'BusinessTypeList',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 模拟业务类型数据
    const mockBusinessTypes = [
      {
        id: 1,
        code: 'A',
        name: '社保业务',
        avgServeTime: 15,
        status: 1,
        description: '社会保险相关业务办理，包括社保卡办理、社保缴费等',
        createTime: '2023-01-10 09:30:22'
      },
      {
        id: 2,
        code: 'B',
        name: '住房公积金',
        avgServeTime: 10,
        status: 1,
        description: '住房公积金账户办理、提取、查询等业务',
        createTime: '2023-01-10 10:15:46'
      },
      {
        id: 3,
        code: 'C',
        name: '医疗保险',
        avgServeTime: 12,
        status: 1,
        description: '医疗保险报销、医保卡办理等服务',
        createTime: '2023-01-11 14:22:35'
      },
      {
        id: 4,
        code: 'D',
        name: '户籍业务',
        avgServeTime: 20,
        status: 0,
        description: '户口迁移、户口本办理等户籍相关业务',
        createTime: '2023-01-12 16:05:12'
      },
      {
        id: 5,
        code: 'E',
        name: '税务办理',
        avgServeTime: 15,
        status: 1,
        description: '个人所得税申报、退税等税务相关业务',
        createTime: '2023-01-15 11:42:58'
      }
    ]
    
    // 业务类型列表数据
    const businessTypeList = ref([...mockBusinessTypes])
    const tableLoading = ref(false)
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: mockBusinessTypes.length
    })
    
    // 过滤表单
    const filterForm = reactive({
      name: '',
      code: '',
      status: ''
    })
    
    // 业务类型对话框
    const businessTypeDialog = reactive({
      visible: false,
      isEdit: false
    })
    
    // 业务类型表单
    const businessTypeFormRef = ref(null)
    const businessTypeForm = reactive({
      id: null,
      code: '',
      name: '',
      avgServeTime: 10,
      status: 1,
      description: ''
    })
    
    // 表单验证规则
    const businessTypeRules = {
      code: [
        { required: true, message: '请输入业务代码', trigger: 'blur' },
        { pattern: /^[A-Za-z]{1,3}$/, message: '业务代码只能是1-3个字母', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入业务名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
      ],
      avgServeTime: [
        { required: true, message: '请输入平均服务时间', trigger: 'blur' },
        { type: 'number', min: 1, message: '平均服务时间必须大于0', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 格式化时间
    const formatTime = (minutes) => {
      if (!minutes || minutes <= 0) return '0分钟'
      return `${minutes}分钟`
    }
    
    // 根据筛选条件和分页显示业务类型列表
    const displayBusinessTypeList = computed(() => {
      // 应用筛选条件
      let filteredList = businessTypeList.value.filter(item => {
        let nameMatch = true, codeMatch = true, statusMatch = true
        
        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }
        
        if (filterForm.code) {
          codeMatch = item.code.includes(filterForm.code)
        }
        
        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }
        
        return nameMatch && codeMatch && statusMatch
      })
      
      // 更新总数
      pagination.total = filteredList.length
      
      // 应用分页
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      
      return filteredList.slice(start, end)
    })
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
    }
    
    // 重置过滤器
    const resetFilter = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = ''
      })
      pagination.currentPage = 1
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }
    
    // 处理刷新
    const handleRefresh = () => {
      tableLoading.value = true
      setTimeout(() => {
        tableLoading.value = false
        ElMessage.success('刷新成功')
      }, 500)
    }
    
    // 处理新建业务类型
    const handleCreateBusinessType = () => {
      businessTypeDialog.isEdit = false
      businessTypeDialog.visible = true
      
      Object.keys(businessTypeForm).forEach(key => {
        if (key === 'avgServeTime') {
          businessTypeForm[key] = 10
        } else if (key === 'status') {
          businessTypeForm[key] = 1
        } else {
          businessTypeForm[key] = ''
        }
      })
    }
    
    // 处理编辑业务类型
    const handleEditBusinessType = (row) => {
      businessTypeDialog.isEdit = true
      businessTypeDialog.visible = true
      
      businessTypeForm.id = row.id
      businessTypeForm.code = row.code
      businessTypeForm.name = row.name
      businessTypeForm.avgServeTime = row.avgServeTime
      businessTypeForm.status = row.status
      businessTypeForm.description = row.description
    }
    
    // 处理删除业务类型
    const handleDeleteBusinessType = (row) => {
      ElMessageBox.confirm(`确定要删除业务类型"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中删除对应业务类型
        const index = businessTypeList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          businessTypeList.value.splice(index, 1)
          ElMessage.success('删除业务类型成功')
        }
      }).catch(() => {})
    }
    
    // 处理切换状态
    const handleToggleStatus = (row) => {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      
      ElMessageBox.confirm(`确定要${statusText}业务类型"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中更新状态
        const index = businessTypeList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          businessTypeList.value[index].status = newStatus
          ElMessage.success(`${statusText}业务类型成功`)
        }
      }).catch(() => {})
    }
    
    // 提交业务类型表单
    const submitBusinessTypeForm = () => {
      businessTypeFormRef.value.validate((valid) => {
        if (valid) {
          const isEdit = businessTypeDialog.isEdit
          
          if (isEdit) {
            // 编辑现有业务类型
            const index = businessTypeList.value.findIndex(item => item.id === businessTypeForm.id)
            if (index !== -1) {
              businessTypeList.value[index] = {
                ...businessTypeList.value[index],
                name: businessTypeForm.name,
                avgServeTime: businessTypeForm.avgServeTime,
                status: businessTypeForm.status,
                description: businessTypeForm.description,
              }
              ElMessage.success('更新业务类型成功')
            }
          } else {
            // 创建新业务类型
            const newId = Math.max(...businessTypeList.value.map(item => item.id), 0) + 1
            const now = new Date()
            const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
            
            businessTypeList.value.push({
              id: newId,
              code: businessTypeForm.code,
              name: businessTypeForm.name,
              avgServeTime: businessTypeForm.avgServeTime,
              status: businessTypeForm.status,
              description: businessTypeForm.description,
              createTime: createTime
            })
            ElMessage.success('创建业务类型成功')
          }
          
          businessTypeDialog.visible = false
        }
      })
    }
    
    onMounted(() => {
      // 初始化时不需要额外操作，模拟数据已加载
    })
    
    return {
      businessTypeList,
      displayBusinessTypeList,
      tableLoading,
      pagination,
      filterForm,
      businessTypeDialog,
      businessTypeFormRef,
      businessTypeForm,
      businessTypeRules,
      formatTime,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateBusinessType,
      handleEditBusinessType,
      handleDeleteBusinessType,
      handleToggleStatus,
      submitBusinessTypeForm
    }
  }
}
</script>

<style scoped>
.business-type-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.business-type-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 